package trading.algo.BearTask;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import trading.algo.TimerKillerTask;
import trading.bo.DBAccessorBO;
import trading.bo.IBAccessorBO;
import trading.util.MarketTimeHelper;
import trading.util.VIXFrontMonthCheckUtil;

public class VIXPricesTask extends TimerTask {
	
	private DBAccessorBO dbAccessorBO;
	private IBAccessorBO ibAccessorBO;
	private MarketTimeHelper marketTimeHelper;

	public VIXPricesTask(DBAccessorBO dbAccessorBO, IBAccessorBO ibAccessorBO, MarketTimeHelper marketTimeHelper) {
		this.dbAccessorBO = dbAccessorBO;
		this.ibAccessorBO = ibAccessorBO;
		this.marketTimeHelper = marketTimeHelper;
	}

	@Override
	public void run() {
		/**
		 * Step 1: get VIX spot price
		 */
		URL url = null;
		try {
			url = new URL(
					"http://download.finance.yahoo.com/d/quotes.csv?s=%5EVIX&e=.csv&f=l1");
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		BufferedReader in;
		String todaysVIXPrice = "";
		try {
			in = new BufferedReader(new InputStreamReader(url.openStream()));
			todaysVIXPrice = in.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		dbAccessorBO.updateVIXSpotPriceTable(todaysVIXPrice);
		/**
		 * Step 2: determine VIX front month expiration
		 */
		System.out.println("Start testing VIX future front month date.");
		VIXFrontMonthCheckUtil.startTestingFrontMonthDate();
		Timer timer = new Timer();
		int taskID = 0;
		
		VIXFuturePriceTask vixFuturePriceTask = new VIXFuturePriceTask(this.ibAccessorBO, this.marketTimeHelper.getThisMonthExpiration());
        timer.schedule(vixFuturePriceTask, taskID * 1000);
        taskID += VIXFuturePriceTask.secondsNeeded();
        
        /**
         * Step 3: store VIX front month and second month future price data
         */
        VIXFutureCheckFrontMonthDateTask checkDateTask = new VIXFutureCheckFrontMonthDateTask(this.ibAccessorBO, marketTimeHelper);
        timer.schedule(checkDateTask, taskID * 1000);
        taskID += VIXFutureCheckFrontMonthDateTask.secondsNeeded();
        
        /**
         * Step 4: reset VIXPricesTask
         */
        VIXPricesTaskFinalizeTask finalizeTask = new VIXPricesTaskFinalizeTask();
        timer.schedule(finalizeTask, taskID * 1000);
        taskID += VIXPricesTaskFinalizeTask.secondsNeeded();
        
        /**
         * Step 5: kill the timer
         */
        TimerKillerTask timerKillerTask = new TimerKillerTask(timer);
        timer.schedule(timerKillerTask, taskID * 1000);
        
	}
	
	public static int secondsNeeded() {
	    return 2 + VIXFuturePriceTask.secondsNeeded() + VIXFutureCheckFrontMonthDateTask.secondsNeeded() + VIXPricesTaskFinalizeTask.secondsNeeded();
	}
}
